<script setup lang="ts">
import type { TextEllProps } from './TextEll.vue'
import { Message } from '@arco-design/web-vue'
import { useClipboard } from '@vueuse/core'

export interface CopyFieldProps extends TextEllProps {
  copyText?: string
  mouseOver?: boolean
  successMessage?: boolean
  hoverTable?: boolean

  href?: string
}

const props = withDefaults(defineProps<CopyFieldProps>(), {
  successMessage: true,
  mouseOver: false,
  hoverTable: false,
})
const { copy } = useClipboard({
  legacy: true,
})
const copyFieldRef = ref<HTMLElement>()
const router = useRouter()
function handleClick() {
  if (props?.href) {
    router.push(props.href)
  }
}
function handleCopy() {
  const { textContent } = copyFieldRef.value?.querySelector('.text-ell') || {
    textContent: '',
  }
  const copyContent = props?.copyText || props?.content || textContent || ''

  copy(String(copyContent)).then(() => {
    if (props.successMessage) {
      Message.success('复制成功')
    }
  })
}
</script>

<template>
  <div
    ref="copyFieldRef"
    class="copy-field__wrapper"
    :class="mouseOver ? 'copy-field-mouse_wrapper' : ''"
  >
    <text-ell
      v-bind="$attrs"
      :class="{ 'cursor-pointer hover:text-primary': href }"
      @click="handleClick"
    >
      <slot>{{ content }}</slot>
    </text-ell>
    <span
      v-if="content && content !== '-' && content !== ''"
      class="copy-icon"
      :class="hoverTable ? 'hover-visible__tr' : ''"
      @click.prevent="handleCopy"
    >
      <slot name="icon">
        <i-icons-copy class="copy-icon" />
      </slot>
    </span>
  </div>
</template>

<style lang="less" scoped>
@copy-size: 16px !important;

.copy-field__wrapper {
  display: flex;
  align-items: center;
  gap: 5px;
  position: relative;

  :deep(.text-ell) {
    flex: initial;
    width: max-content;
  }
}

.copy-icon {
  width: @copy-size;
  height: @copy-size;
  color: rgb(var(--primary-6));
  cursor: pointer;
  transition: color 0.2s;
  // bottom: 4px;

  &:hover {
    color: rgb(var(--primary-8));
  }

  svg {
    width: @copy-size;
    height: @copy-size;
  }
}

.arco-table-tr {
  .copy-icon {
    @apply !hidden;
  }

  &:hover {
    .copy-icon {
      @apply !inline-flex;
      position: relative;
    }
  }
}

.copy-field-mouse_wrapper {
  .copy-icon {
    @apply hidden;
  }

  &:hover {
    .copy-icon {
      @apply inline-block;
    }
  }
}
</style>
